<script setup lang="ts">
import { ref } from 'vue';
import { useQuasar } from 'quasar';
import { useUserStore } from '../stores/user';
import { register, login } from '../api/user';

const $q = useQuasar();
const userStore = useUserStore();

// 表单数据
const formData = ref({
  username: '',
  phone: '',
  password: '',
  confirmPassword: ''
});

// 登录方式：'username' 或 'phone'
const loginType = ref('username');

// 是否显示注册表单
const isRegister = ref(false);

// 表单验证规则
const rules = {
  username: [
    (val: string) => !!val || '请输入用户名',
    (val: string) => val.length >= 3 || '用户名至少3个字符',
    (val: string) => val.length <= 20 || '用户名最多20个字符'
  ],
  phone: [
    (val: string) => !!val || '请输入手机号',
    (val: string) => /^1[3-9]\d{9}$/.test(val) || '请输入正确的手机号'
  ],
  password: [
    (val: string) => !!val || '请输入密码',
    (val: string) => val.length >= 6 || '密码至少6个字符',
    (val: string) => val.length <= 20 || '密码最多20个字符'
  ],
  confirmPassword: [
    (val: string) => !!val || '请确认密码',
    (val: string) => val === formData.value.password || '两次输入的密码不一致'
  ]
};

// 处理注册
const handleRegister = async () => {
  try {
    const { username, phone, password } = formData.value;
    const response = await register({ username, phone, password });
    userStore.setToken(response.token);
    userStore.setUser(response.user);
    $q.notify({
      message: '注册成功！',
      color: 'positive'
    });
    isRegister.value = false;
  } catch (error) {
    $q.notify({
      message: '注册失败：' + (error as Error).message,
      color: 'negative'
    });
  }
};

// 处理登录
const handleLogin = async () => {
  try {
    const { username, phone, password } = formData.value;
    const loginData = loginType.value === 'username'
      ? { username, password }
      : { phone, password };
    const response = await login(loginData);
    userStore.setToken(response.token);
    userStore.setUser(response.user);
    $q.notify({
      message: '登录成功！',
      color: 'positive'
    });
  } catch (error) {
    $q.notify({
      message: '登录失败：' + (error as Error).message,
      color: 'negative'
    });
  }
};

// 切换登录方式
const toggleLoginType = () => {
  loginType.value = loginType.value === 'username' ? 'phone' : 'username';
};

// 切换注册/登录表单
const toggleForm = () => {
  isRegister.value = !isRegister.value;
  formData.value = {
    username: '',
    phone: '',
    password: '',
    confirmPassword: ''
  };
};
</script>

<template>
  <div class="user-auth">
    <q-card class="auth-card">
      <q-card-section>
        <div class="text-h6 text-center q-mb-md">
          {{ isRegister ? '用户注册' : '用户登录' }}
        </div>

        <!-- 登录表单 -->
        <div v-if="!isRegister">
          <q-form @submit="handleLogin" class="q-gutter-md">
            <!-- 登录方式切换 -->
            <div class="row justify-end">
              <q-btn
                flat
                dense
                :label="loginType === 'username' ? '使用手机号登录' : '使用用户名登录'"
                @click="toggleLoginType"
                color="primary"
              />
            </div>

            <!-- 用户名登录 -->
            <q-input
              v-if="loginType === 'username'"
              v-model="formData.username"
              label="用户名"
              :rules="rules.username"
              outlined
            />

            <!-- 手机号登录 -->
            <q-input
              v-else
              v-model="formData.phone"
              label="手机号"
              :rules="rules.phone"
              outlined
            />

            <q-input
              v-model="formData.password"
              type="password"
              label="密码"
              :rules="rules.password"
              outlined
            />

            <div class="row justify-between items-center">
              <q-btn
                label="注册新账号"
                flat
                color="primary"
                @click="toggleForm"
              />
              <q-btn
                label="登录"
                type="submit"
                color="primary"
              />
            </div>
          </q-form>
        </div>

        <!-- 注册表单 -->
        <div v-else>
          <q-form @submit="handleRegister" class="q-gutter-md">
            <q-input
              v-model="formData.username"
              label="用户名"
              :rules="rules.username"
              outlined
            />

            <q-input
              v-model="formData.phone"
              label="手机号"
              :rules="rules.phone"
              outlined
            />

            <q-input
              v-model="formData.password"
              type="password"
              label="密码"
              :rules="rules.password"
              outlined
            />

            <q-input
              v-model="formData.confirmPassword"
              type="password"
              label="确认密码"
              :rules="rules.confirmPassword"
              outlined
            />

            <div class="row justify-between items-center">
              <q-btn
                label="返回登录"
                flat
                color="primary"
                @click="toggleForm"
              />
              <q-btn
                label="注册"
                type="submit"
                color="primary"
              />
            </div>
          </q-form>
        </div>
      </q-card-section>
    </q-card>
  </div>
</template>

<style scoped>
.user-auth {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}

.auth-card {
  border-radius: 8px;
}
</style> 